import http.client
import json
import os
class PostAudio:
    #替换为自己的阿里云语言识别key token
    appKey = '*******'
    token = '******'
    # 服务请求地址
    url = 'https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr'
    # 音频文件
    audioFile =os.getcwd() + r'/recording.wav'
    format = 'pcm'
    sampleRate = 16000
    enablePunctuationPrediction = True
    enableInverseTextNormalization = True
    enableVoiceDetection = False
    # 设置RESTful请求参数
    request = url + '?appkey=' + appKey
    request = request + '&format=' + format
    request = request + '&sample_rate=' + str(sampleRate)

    if enablePunctuationPrediction:
        request = request + '&enable_punctuation_prediction=' + 'true'

    if enableInverseTextNormalization:
        request = request + '&enable_inverse_text_normalization=' + 'true'

    if enableVoiceDetection:
        request = request + '&enable_voice_detection=' + 'true'
    def __init__(self):
        pass
    def process(self):

        # 读取音频文件
        with open(self.audioFile, mode='rb') as f:
            audioContent = f.read()

        host = 'nls-gateway.cn-shanghai.aliyuncs.com'

        # 设置HTTPS请求头部
        httpHeaders = {
            'X-NLS-Token': self.token,
            'Content-type': 'application/octet-stream',
            'Content-Length': len(audioContent)
        }

        # Python 2.x使用httplib
        # conn = httplib.HTTPConnection(host)

        # Python 3.x使用http.client
        conn = http.client.HTTPConnection(host)

        conn.request(method='POST', url=self.request, body=audioContent, headers=httpHeaders)

        response = conn.getresponse()
        print('Response status and response reason:')
        print(response.status, response.reason)

        body = response.read()
        try:
            print('Recognize response is:')
            body = json.loads(body)
            print(body)

            status = body['status']
            if status == 20000000:
                result = body['result']
                print('Recognize result: ' + result)
                conn.close()
                return result
            else:
                print('Recognizer failed!')
                conn.close()
                return False

        except ValueError:
            print('The response is not json format string')

